import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { usePermissionStore } from '@/store/permission'

// 静态路由
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', requiresAuth: false }
  },
  {
    path: '/',
    name: 'MainLayout',
    component: () => import('@/layouts/Index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: {
          title: '首页',
          icon: 'House',
          affix: true
        }
      },
      {
        path: 'profile',
        name: 'profile',
        component: () => import('@/views/profile/index.vue'),
        meta: {
          title: '个人信息页',
          icon: 'User'
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes
})

// 权限控制
export function hasPermission(permission: string | undefined) {
  const userStore = useUserStore()
  if (!permission) return true
  return userStore.permissions.includes(permission)
}

// 过滤路由
export function filterAsyncRoutes(routes: RouteRecordRaw[], permissions: string[]) {
  const res: RouteRecordRaw[] = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (!tmp.meta?.permission || permissions.includes(tmp.meta.permission)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, permissions)
      }
      res.push(tmp)
    }
  })

  return res
}

// 配置进度条
NProgress.configure({
  showSpinner: false,
  minimum: 0.3,
  easing: 'ease',
  speed: 500
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  const userStore = useUserStore()
  const permissionStore = usePermissionStore()

  // 如果是登录页
  if (to.path === '/login') {
    userStore.token ? next('/') : next()
    NProgress.done()
    return
  }

  // 如果没有token，跳转到登录页
  if (!userStore.token) {
    next(`/login?redirect=${to.fullPath}`)
    NProgress.done()
    return
  }

  try {
    // 如果没有路由或权限信息，初始化路由
    if (!permissionStore.dynamicRoutes.length || !userStore.permissions.length) {
      // 初始化路由
      await permissionStore.initRoutes()
      // 重新导航到目标路由
      next({ ...to, replace: true })
      return
    }

    // 检查路由是否存在
    if (to.matched.length === 0) {
      // 如果路由不存在，可能是动态路由还没有加载完成
      // 重新初始化路由
      await permissionStore.initRoutes()
      // 再次尝试导航
      if (router.hasRoute(to.name!)) {
        next({ ...to, replace: true })
      } else {
        // 如果路由仍然不存在，跳转到404
        next('/404')
      }
      return
    }

    // 正常导航
    next()
  } catch (error) {
    console.error('Route guard error:', error)
    // 发生错误时清理登录状态
    userStore.token = ''
    localStorage.removeItem('token')
    next(`/login?redirect=${to.fullPath}`)
  } finally {
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router 